﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace CHS.ChengDu.Service.Interface.LIS
{
    public class Report
    {


        /// <summary>
        /// 
        /// </summary>
        /// <param name="readID"></param>
        public string Print(string readID)
        {           
           return  CallAutoPrintReport(readID);
        }

        [DllImport("kernel32.dll", EntryPoint = "LoadLibrary")]
        static extern int LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string lpLibFileName);

        [DllImport("kernel32.dll", EntryPoint = "GetProcAddress")]
        static extern IntPtr GetProcAddress(int hModule, [MarshalAs(UnmanagedType.LPStr)] string lpProcName);

        [DllImport("kernel32.dll", EntryPoint = "FreeLibrary")]
        static extern bool FreeLibrary(int hModule);

        [UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Ansi)]
        delegate  IntPtr AutoPrintReport([MarshalAs(UnmanagedType.LPStr)] string inputString);

        public static string CallAutoPrintReport(string inputString)
        {
            const string dllName = "HisPrintReport.dll";
            const string functionName = "AutoPrintReport";

            int libHandle = LoadLibrary(dllName);
            if (libHandle == 0)
                throw new Exception(string.Format("Could not load library \"{0}\"", dllName));
            
            var outputString = "";
            try
            {
                var delphiFunctionAddress = GetProcAddress(libHandle, functionName);
                if (delphiFunctionAddress == IntPtr.Zero)
                    throw new Exception(string.Format("Can't find function \"{0}\" in library \"{1}\"", functionName, dllName));

                var delphiFunction = (AutoPrintReport)Marshal.GetDelegateForFunctionPointer(delphiFunctionAddress, typeof(AutoPrintReport));
                IntPtr output = Marshal.AllocCoTaskMem(1000);
                output =  delphiFunction(inputString);
                if (output ==null)
                    throw new Exception("打印失败");
                outputString = Marshal.PtrToStringAnsi(output);
            }
            finally
            {
                FreeLibrary(libHandle);
            }
            return outputString;
        }
    }
}

